# _*_ coding:utf-8 _*_
# @Time  : 2023.11.08
# @Author: zizlee
from fastapi import APIRouter, Header, Body, Query
from pydantic import BaseModel
from db import FAConnection
from hutool import security
from v1_all_api.all_utils import datetime_utils
from v1_all_api.constant import WORK_MISTAKE_TYPE, WORK_GROUPS
from v1_all_api.all_response import AllResponse

mistake_api = APIRouter()


class MistakeItem(BaseModel):
    mistake_date: str
    mistake_name: str
    mistake_uid: int
    mistake_group: str
    mistake_type: int
    mistake_desc: str
    discovery_name: str


@mistake_api.post('/new/')
def create_mistake(ruizy_token: str = Header(...), mistake: MistakeItem = Body(...)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    # 创建记录
    sql = """
        INSERT INTO work_mistake (mistake_date,mistake_name,mistake_uid,mistake_group,mistake_type,mistake_desc,discovery_name,
        create_name,create_id,update_name,update_id) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);
    """
    prm = [mistake.mistake_date, mistake.mistake_name, mistake.mistake_uid, mistake.mistake_group, mistake.mistake_type, mistake.mistake_desc, mistake.discovery_name]
    with FAConnection() as cursor:
        cursor.execute("SELECT admin_name FROM ruizy_user WHERE id=%s;", [person['uid']])
        creator = cursor.fetchone()
        if not creator:
            return AllResponse.no_authorization()
        prm.extend([creator['admin_name'], person['uid'], creator['admin_name'], person['uid']])
        c = cursor.execute(sql, prm)
    return AllResponse.operate_successfully(msg=f'创建完成，影响记录数:{c}条.')


@mistake_api.get('/my/')
def retrieve_mistake_of_me(ruizy_token: str = Header(...), page: int = Query(1), page_size: int = Query(30)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    sql = """
        SELECT id,mistake_date,mistake_type,mistake_desc,discovery_name FROM work_mistake WHERE mistake_uid=%s;
    """
    with FAConnection() as cursor:
        ret = cursor.self_conn.query_paginator(sql, [person['uid']], page=page, page_size=page_size, keep_conn=True)
    for item in ret['data']:
        item['mistake_type_name'] = WORK_MISTAKE_TYPE.get(item['mistake_type'])
    return AllResponse.operate_successfully(data=ret)


@mistake_api.get('/statistics/')  # st统计方式，默认方式=0=部门统计，1=小组统计，2=个人统计
def statistics_mistake(ruizy_token: str = Header(...),
                       start: str = Query(...), end: str = Query(...), st: int = Query(0, ge=0, le=2)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    start_date = datetime_utils.auth_datetime_string(start, f='%Y-%m-%d')
    end_date = datetime_utils.auth_datetime_string(end, f='%Y-%m-%d')
    security.operator_is_manager(person)
    p_sql = """
        SELECT ru.id,ru.role_code,ux.group_en,ux.is_leader
        FROM ruizy_user As ru
        LEFT JOIN work_user_extend As ux ON ru.id=ux.user_id
        WHERE ru.id=%s;
    """
    mistake_sql = """
        SELECT id,mistake_date,mistake_name,mistake_uid,mistake_group,mistake_type,mistake_desc,discovery_name
        FROM work_mistake WHERE mistake_date>=%s AND mistake_date<=%s AND del_id IS NULL;
    """
    with FAConnection() as cursor:
        cursor.execute(p_sql, [person['uid']])
        operator = cursor.fetchone()
        if not operator:
            return AllResponse.no_authorization()
        cursor.execute(mistake_sql, [start_date, end_date])
        mistake_list = list(cursor.fetchall())
    # 超级管理员返回部门统计
    if security.operator_is_manager(operator) and st == 0:
        pass
    # 组长返回组员统计
    elif operator['is_leader'] and st == 1:
        mistake_list = list(filter(lambda x: x['mistake_group'] == operator['group_en'], mistake_list))
    # 个人返回自己的统计
    else:
        mistake_list = list(filter(lambda x: x['mistake_uid'] == operator['id'], mistake_list))

    stat_dict = {}
    for item in mistake_list:
        item['mistake_date'] = str(item['mistake_date'])
        item['group_name'] = WORK_GROUPS.get(item['mistake_group'])
        item['mistake_type_name'] = WORK_MISTAKE_TYPE.get(item['mistake_type'])

        uid = item['mistake_uid']
        if uid not in stat_dict.keys():
            stat_dict[uid] = {
                'user_id': uid,
                'user_name': item['mistake_name'],
                'user_group': item['mistake_group'],
                'group_name': WORK_GROUPS.get(item['mistake_group']),
                'count': 1,
                'rows': [item]
            }
        else:
            u_stat = stat_dict[uid]
            u_stat['count'] += 1
            u_stat['rows'].append(item)

    stat_list = [v for _, v in stat_dict.items()]
    stat_list.sort(key=lambda x: x['count'], reverse=True)
    return AllResponse.operate_successfully(data=stat_list)
